<?php
//require("Constants.php");

class CommonUtils {

	var $datasec  = array();
	var $ctrl_dir = array();
	var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
	var $old_offset   = 0;

	function getTextAnswer($a){
		switch($a){
			case 0:
				return 'A';
			case 1:
				return 'B';
			case 2:
				return 'C';
			case 3:
				return 'D';

		}
	}
	function generateID(){
		$magic = "KHANGHY";
		date_default_timezone_set('Asia/Saigon');
		return md5(uniqid($magic . date('Ymd') .rand()));
	}
	function zenCode($code)
	{
		date_default_timezone_set('Asia/Saigon');
		return $code.date('YmdHis');
	}
	function checkOverlap($fDate, $toDate, $fromCheck, $toCheck){
		if (($this->compareDate($fDate, $toCheck) >= 0) || ($this->compareDate($fromCheck, $toDate) >= 0)){
			return false;
		}
		return true;
	}


	function formatDate($date, $format) {
		if (trim($date) == "")
		return "";
		$y = substr($date, 0, 4);
		$m = substr($date, 5, 2);
		$d = substr($date, 8, 2);
		$s = (int) substr($date, -2, 2);
		$i = (int) substr($date, -5, 2);
		$h = (int) substr($date, -7, 2);
		return date($format, mktime($h,$i,$s,$m,$d,$y));
	}

	function compareDate($date1, $date2) {
		$y1 = substr($date1, 0, 4);
		$m1 = substr($date1, 5, 2);
		$d1 = substr($date1, 8, 2);
		$y2 = substr($date2, 0, 4);
		$m2 = substr($date2, 5, 2);
		$d2 = substr($date2, 8, 2);
		if ($y1 < $y2) return -1;
		else if($y1 > $y2) return 1;
		else {
			if ($m1 < $m2) return -1;
			else if ($m1 > $m2) return 1;
			else {
				if ($d1 < $d2) return -1;
				else if($d1 > $d2) return 1;
				else return 0;
			}
		}
		return 0;
	}
	function formatDecNumber($value,$point=0){
		$res = number_format($value, $point, '.', ',');
		return $curr . $res;
	}
	function duration($date1, $date2, $split = "/"){
		$date1 = substr($date1, 0, 10);
		$date2 = substr($date2, 0, 10);
			

		list($y1, $m1, $d1) = explode($split, $date1);
		list($y2, $m2, $d2) = explode($split, $date2);

		$res =  (int)((mktime(23, 59, 59, $m1, $d1, $y1) - mktime(0, 0, 0, $m2, $d2, $y2)) / (24 * 3600));

		return $res;
	}

	/**
	 * @desc Funtion addDate
	 *       $date : Y-m-d
	 */
	function addDate($date, $more = 0){
		if ($date == ""){
			return "";
		}
		list($y, $m, $d) = explode('-', $date);
		$res = date("Y-m-d", mktime(0, 0, 0, $m, $d, $y) + $more * 3600 * 24);
		return $res;
	}

	function randomNumber($number)
	{
		if($number)
		{
			$total = "";
			for($i=1;$i<=$number;$i++)
			{
				$nr=rand(0,9);
				$total=$total.$nr;
			}
		}
		return $total;
	}

	function formatCurrency($value, $curr = 'VND'){
		$res = number_format($value, 0, '.', ',');
		return $res . " " . $curr;
	}


	function delfile($filename, $path) {
		$delres = @unlink($path . "/" .  $filename);
		if ($delres) {
			return SUCC;
		}
		else {
			return ERROR;
		}
	}

	function uploadfile($source, $des, $path, $width, $height, $max_size){
		$default_extension = ".gif";
		$mode = 1;
		$my_uploader = new Uploader("en");
		$my_uploader->max_filesize($max_size); // 1000KB = 1000000
		$my_uploader->max_image_size($width, $height);
		$my_uploader->setDesFileName($des);
		if ($my_uploader->upload($source, "", $default_extension)) {
			$my_uploader->save_file($path, $mode);
		}
		if ($my_uploader->error) {
			return $my_uploader->error;
		}
		return SUCC;
	}

	function isImageFile($extension){
		if ($extension == ".jpg" || $extension == ".png" || $extension == ".gif" || $extension == ".bmp"
		|| $extension == ".JPG" || $extension == ".PNG" || $extension == ".GIF" || $extension == ".BMP" ){
			return true;
		}
		return false;
	}
	function readImagesFile($dir){
		$result = array();
		$handle = opendir($dir);
		$i = 0;
		if ($handle) {
			while(false !== ($file = readdir($handle))){
				$extension = substr($file, -4, 4);
				if ($this->isImageFile($extension)){
					$result[] = $file;
				}
			}
		}
		return $result;
	}
	function randNum(){
		mt_srand((double)microtime()*1000000);
		$num = mt_rand(46,122);
		return $num;
	}
	function randChar(){
		do {
			$num = $this->randNum();
		} while ( ( $num > 57 && $num < 65 ) || ( $num > 90 && $num < 97 ) );
		$char = chr($num);
		return $char;
	}
	//Function: genSalt
	//Description: Randomize tring for encryption
	function genSalt(){
		$a = $this->randChar();
		$b = $this->randChar();
		$salt = "$a$b";
		return $salt;
	}


	function isFile($extension){
		if ($extension == ".jpg" || $extension == ".png" || $extension == ".gif" || $extension == ".bmp" || $extension==".txt"){
			return true;
		}
		return false;
	}

	function isFlashFile($extension){
		if($extension == ".swf")
		return true;
		return false;
	}
	function readFlashFile($dir){
		$result = array();
		$handle = opendir($dir);
		$i = 0;
		if ($handle) {
			while(false !== ($file = readdir($handle))){
				$extension = substr($file, -4, 4);
				if ($this->isFlashFile($extension)){
					$result[] = $file;
				}
			}
		}
		return $result;
	}
	function readFile($dir){
		$result = array();
		$handle = opendir($dir);
		$i = 0;
		if ($handle) {
			while(false !== ($file = readdir($handle))){
				$extension = substr($file, -4, 4);
				if ($this->isFile($extension)){
					$result[] = $file;
				}
			}
		}
		return $result;
	}
	//Zip File Function
	function unix2DosTime($unixtime = 0) {
		$timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

		if ($timearray['year'] < 1980) {
			$timearray['year']    = 1980;
			$timearray['mon']     = 1;
			$timearray['mday']    = 1;
			$timearray['hours']   = 0;
			$timearray['minutes'] = 0;
			$timearray['seconds'] = 0;
		} // end if

		return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
		($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
	}
	function addFile($data, $name, $time = 0)
	{
		$name     = str_replace('\\', '/', $name);

		$dtime    = dechex($this->unix2DosTime($time));
		$hexdtime = '\x' . $dtime[6] . $dtime[7]
		. '\x' . $dtime[4] . $dtime[5]
		. '\x' . $dtime[2] . $dtime[3]
		. '\x' . $dtime[0] . $dtime[1];
		eval('$hexdtime = "' . $hexdtime . '";');

		$fr   = "\x50\x4b\x03\x04";
		$fr   .= "\x14\x00";            // ver needed to extract
		$fr   .= "\x00\x00";            // gen purpose bit flag
		$fr   .= "\x08\x00";            // compression method
		$fr   .= $hexdtime;             // last mod time and date

		// "local file header" segment
		$unc_len = strlen($data);
		$crc     = crc32($data);
		$zdata   = gzcompress($data);
		$zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
		$c_len   = strlen($zdata);
		$fr      .= pack('V', $crc);             // crc32
		$fr      .= pack('V', $c_len);           // compressed filesize
		$fr      .= pack('V', $unc_len);         // uncompressed filesize
		$fr      .= pack('v', strlen($name));    // length of filename
		$fr      .= pack('v', 0);                // extra field length
		$fr      .= $name;

		// "file data" segment
		$fr .= $zdata;

		// "data descriptor" segment (optional but necessary if archive is not
		// served as file)
		$fr .= pack('V', $crc);                 // crc32
		$fr .= pack('V', $c_len);               // compressed filesize
		$fr .= pack('V', $unc_len);             // uncompressed filesize

		// add this entry to array
		$this -> datasec[] = $fr;

		// now add to central directory record
		$cdrec = "\x50\x4b\x01\x02";
		$cdrec .= "\x00\x00";                // version made by
		$cdrec .= "\x14\x00";                // version needed to extract
		$cdrec .= "\x00\x00";                // gen purpose bit flag
		$cdrec .= "\x08\x00";                // compression method
		$cdrec .= $hexdtime;                 // last mod time & date
		$cdrec .= pack('V', $crc);           // crc32
		$cdrec .= pack('V', $c_len);         // compressed filesize
		$cdrec .= pack('V', $unc_len);       // uncompressed filesize
		$cdrec .= pack('v', strlen($name) ); // length of filename
		$cdrec .= pack('v', 0 );             // extra field length
		$cdrec .= pack('v', 0 );             // file comment length
		$cdrec .= pack('v', 0 );             // disk number start
		$cdrec .= pack('v', 0 );             // internal file attributes
		$cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set

		$cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
		$this -> old_offset += strlen($fr);

		$cdrec .= $name;

		$this -> ctrl_dir[] = $cdrec;
	}
	function file()
	{
		$data    = implode('', $this -> datasec);
		$ctrldir = implode('', $this -> ctrl_dir);

		return
		$data .
		$ctrldir .
		$this -> eof_ctrl_dir .
		pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
		pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
		pack('V', strlen($ctrldir)) .           // size of central dir
		pack('V', strlen($data)) .              // offset to start of central dir
            "\x00\x00";                             // .zip file comment length
	}
	function addFiles($files /*Only Pass Array*/)
	{
		foreach($files as $file)
		{
			if (is_file($file)) //directory check
			{
				$data = implode("",file($file));
				$this->addFile($data,$file);
			}
		}
	}
	/*
	 function doZipFile($filesrc, $filedes): nen file
	 $filesrc : la danh sach cac file can nen: phai la array
	 $filedes : ten file dich
	 VD:
	 $utils = new CommonUtils();
	 u$tils->doZipFile(array("a.txt","b.png"),"data/des.zip");

	 */
	function doZipFile($filesrc, $filedes)
	{
		foreach($filesrc as $file)
		{
			if (is_file($file)) //directory check
			{
				$data = implode("",file($file));
				$this->addFile($data,$file);
			}
		}
		//out file
		$fp=fopen($filedes,"w");
		if(file_exists($filedes))
		{
			fwrite($fp,$this->file());
			fclose($fp);
		}
		else
		echo $nls_file_noexit;
	}
	//End Zip Function
	//Unzip Function


	/**
	 * Redirect URL
	 */


	function redirect($url){
		if(headers_sent()){
			echo "<script>document.location.href='$url';</script>";
		}else{
			header( 'HTTP/1.1 301 Moved Permanently' );
			header("Location: " . $url);
		}
	}

	/**
	 * @desc Get message from code of authentication code
	 */
	function getMessage($code){
		global $nls_login_error, $nls_need_login_error, $nls_login_fail, $nls_login_blocked,
		$nls_login_not_activiated, $nls_login_not_right_perm, $nls_login_empty;
		switch($code){
			case SESSION_TIMEOUT:
				return $nls_login_session_timeout;
			case NOT_LOGON:
				return $nls_need_login_error;
			case WRONG_USER_PWD:
				return $nls_login_fail;
			case BLOCKED_ERROR:
				return $nls_login_blocked;
			case NOT_ACTIVIATED:
				return $nls_login_not_activiated;
			case NOT_RIGHT_PERM:
				return $nls_login_not_right_perm;
			case EMPTY_USER_PWD:
				return $nls_login_empty;
		}

	}


	/**
	 * @desc Order Code with 8 digit
	 */
	function generateCode(){
		$res = "";
		for($i = 0; $i < 8; $i++){
			mt_srand((double)microtime()*1000000);
			$res .= mt_rand(0,9);
		}
		return $res;
	}

	function getNumDayOfMonth($month, $year){
		switch($month){
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				return 31;
			case 4:
			case 6:
			case 9:
			case 11:
				return 30;
			case 2:
				if (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0){
					return 29;
				}
				return 28;
		}
	}

	function getStartDayOfMonth($month, $year){
		$date = date("Y-m-d", mktime(0, 0, 0, $month, 1, $year));
		return $date["wday"];
	}

	function getParameter($name, $default = null) {
		$result = isset($_GET[$name]) ? $_GET[$name] : null;
		if (!isset($result)) {
			$result = isset($_POST[$name]) ? $_POST[$name] : null;
		}
		if (!isset($result)) return $default;
		return $result;
	}
	function formatInputStr($str)
	{
		$str=stripslashes($str);
		$str=addslashes($str);
		return $str;
	}
	function pdf_create($html, $filename, $stream="F"){
			
		ini_set("memory_limit", "712M");
		ini_set("max_execution_time",60*10);
		//include('tcpdf/tcpdf.php');
		include  ('tcpdf/tcpdf.php');
		include('tcpdf/config/lang/eng.php');
			
		$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		$htmlcss = <<<EOF
<!-- EXAMPLE OF CSS STYLE -->
<style type="text/css">
	table
        {
            width:	98%;
            border-spacing: 2px 2px;
            border-collapse: separate;
            border:1px #909090 solid;
        }
	tr
        {
            border-color: inherit;
            display: table-row;
            vertical-align: inherit;
        }
	td
        {
            text-align:	left;
        }
        table.page_header {width: 100%; border: none;  border-bottom: solid 1mm #AAAADD; padding: 2mm }
        table.expdetail
        {
            border-spacing: 0px 0px;
            border-collapse: collapse;
            border:1px #909090 solid;
            align:center;
            width:98%;
        }
        table.title
        {
            border-spacing: 0px 0px;
            border-collapse: collapse;
            border:1px #909090 solid;
            width:100%;
        }
        table.expcontent
        {
            border-spacing: 0px 0px;
            border-collapse: collapse;
            border:1px #909090 solid;
            width:100%;
        }
        .expcontent td 
        {
            border:0.1px #909090 solid;
            text-align:left;
            font-size: 12pt;
            cellspacing:0
            cellpadding:0
        }
        table.expcontentchild
        {
            width: 100%;
            border-spacing: 0px 0px;
            border-collapse: collapse;
            border:1px #909090 solid;
        }
        .expcontentchild td
        {
            border:1px #909090 solid;
            text-align:left;
            font-size: 12pt;
            cellspacing:0
            cellpadding:0
        }
        .explogo
        {
            width:40px;
            height:40px;
        }
        strong#titles{
            font-size: 18pt;
        }
</style>
EOF;

		// set default header data
		$pdf->SetHeaderData($this->logo, PDF_HEADER_LOGO_WIDTH, '','');

		// set header and footer fonts
		$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
		//  $pdf->Ln();
		// set default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

		//set margins
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		//set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

		//set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		//set some language-dependent strings
		$l = Array();

		// PAGE META DESCRIPTORS --------------------------------------

		$l['a_meta_charset'] = 'UTF-8';
		$l['a_meta_dir'] = 'ltr';
		$l['a_meta_language'] = 'en';
		$l['w_page'] = 'page';
			
		$pdf->setLanguageArray($l);

		// ---------------------------------------------------------

		// set default font subsetting mode
		$pdf->setFontSubsetting(true);

		// Set font
		// dejavusans is a UTF-8 Unicode font, if you only need to
		// print standard ASCII chars, you can use core fonts like
		// helvetica or times to reduce file size.
		//$pdf->SetFont('dejavusans', '', 11, '', true);
		$pdf->SetFont('helvetica', '', 10);
		// Add a page
		// This method has several options, check the source code documentation for more information.
		$pdf->AddPage();

		$pdf->writeHTML($html, true, true, true, true, '');

		// ---------------------------------------------------------
		ob_clean();
		$pdf->Output($filename.".pdf", 'D');
	}
	function getDate(){
		date_default_timezone_set('Asia/Saigon');
		$date = date('Y-m-d h:i:s ', time());
		return $date;
	}
}
?>